﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Runtime.InteropServices;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using Microsoft.Win32;

namespace RedditWallpaperLib
{
    public class RedditWallpaper
    {
        private const string REDDIT_URL = @"http://www.reddit.com/r/wallpapers/hot";
        private const int SPI_SETDESKWALLPAPER = 20;
        private const int SPIF_UPDATEINIFILE = 0x01;
        private const int SPIF_SENDWININICHANGE = 0x02;

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);

        private WebClient webClient;

        public RedditWallpaper()
        {
            webClient = new WebClient();
        }

        public void ChangeWallpaper()
        {
            string wallpaperUrl = GetWallpaperUrl();            

            SetWallpaper( wallpaperUrl);
        }

        private string GetWallpaperUrl()
        {
            string htmlSource = webClient.DownloadString(REDDIT_URL);

            string[] parsedSource = htmlSource.Split('\"');
            string topImgurLink = null;

            for (int i = 0; i < parsedSource.Length; i++)
            {
                if (parsedSource[i].Contains(@"http://i.imgur.com/"))
                {
                    topImgurLink = parsedSource[i];
                    break;
                }
            }

            if (topImgurLink == null)
            {
                throw new Exception("Unable to find wallpaper url!");
            }

            return topImgurLink;
        }

        private void SetWallpaper(string url)
        {                    
            Stream stream = webClient.OpenRead(url);     
            
            Image wallpaperImage = Image.FromStream(stream);

            string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp");
            wallpaperImage.Save(tempPath, ImageFormat.Bmp);

            RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
            key.SetValue(@"WallpaperStyle", 2.ToString());
            key.SetValue(@"TileWallpaper", 0.ToString());

            SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, tempPath, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
        }
    }
}
